package com.canaan.business.service.inOutStock.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.canaan.business.common.enums.basic.StorehousePermissionEnum;
import com.canaan.business.common.enums.basic.YNEnum;
import com.canaan.business.common.enums.inOutStock.*;
import com.canaan.business.common.enums.storehouse.StoreHouseTypeEnum;
import com.canaan.business.common.enums.storehouse.StorehouseStockStatusEnum;
import com.canaan.business.domain.basic.StorehousePermission;
import com.canaan.business.domain.basic.WmsStorehouse;
import com.canaan.business.domain.bill.AdjustOutBill;
import com.canaan.business.domain.bill.PickProductBill;
import com.canaan.business.domain.bill.PurchaseReturnBill;
import com.canaan.business.domain.inOutStock.*;
import com.canaan.business.domain.invoice.WmsSalesOrder;
import com.canaan.business.domain.storehouse.WmsStorehouseStock;
import com.canaan.business.domain.vo.OutStockDetailOrderAvailableQtyVo;
import com.canaan.business.domain.vo.distributePickerVo;
import com.canaan.business.mapper.inOutStock.WmsOutStockDetailOrderMapper;
import com.canaan.business.service.basic.IStorehousePermissionService;
import com.canaan.business.service.basic.IWmsStorehouseService;
import com.canaan.business.service.bill.IAdjustOutBillService;
import com.canaan.business.service.bill.IPickProductBillService;
import com.canaan.business.service.bill.IPurchaseReturnBillService;
import com.canaan.business.service.inOutStock.*;
import com.canaan.business.service.invoice.IWmsSalesOrderService;
import com.canaan.business.service.storehouse.IWmsStorehouseStockService;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.DateUtils;
import com.canaan.common.utils.SecurityUtils;
import com.canaan.common.utils.StringUtils;
import com.canaan.common.utils.TableNoUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import oshi.driver.mac.net.NetStat;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 出库单明细Service业务层处理
 *
 * @author ruoyi
 * @date 2022-12-20
 */
@Service
public class WmsOutStockDetailOrderServiceImpl implements IWmsOutStockDetailOrderService
{
    @Resource
    private WmsOutStockDetailOrderMapper wmsOutStockDetailOrderMapper;
    @Resource
    private IWmsOutStockOrderService wmsOutStockOrderService;
    @Resource
    private IPickerTaskOrderService pickerTaskOrderService;
    @Resource
    private IWmsStorehouseStockService wmsStorehouseStockService;
    @Resource
    private IWmsStockOccupyService wmsStockOccupyService;
    @Resource
    private IStorehousePermissionService storehousePermissionService;

    @Resource
    private IWmsSalesOrderService wmsSalesOrderService;
    @Resource
    private IPickProductBillService pickProductBillService;
    @Resource
    private IAdjustOutBillService adjustOutBillService;
    @Resource
    private IPurchaseReturnBillService purchaseReturnBillService;
    @Resource
    private IWmsStorehouseService wmsStorehouseService;
    @Resource
    private IStorehouseStockCheckService storehouseStockCheckService;
    @Resource
    private IStockOccupyDetailService stockOccupyDetailService;
    /**
     * 查询出库单明细
     *
     * @param id 出库单明细主键
     * @return 出库单明细
     */
    @Override
    public WmsOutStockDetailOrder selectWmsOutStockDetailOrderById(Long id)
    {
        return wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderById(id);
    }

    /**
     * 查询出库单明细
     *
     * @param no 出库单明细编号
     * @return 出库单明细
     */
    @Override
    public WmsOutStockDetailOrder selectWmsOutStockDetailOrderByNo(String no)
    {
        return wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderByNo(no);
    }

    /**
     * 查询出库单明细列表
     *
     * @param wmsOutStockDetailOrder 出库单明细
     * @return 出库单明细
     */
    @Override
    public List<WmsOutStockDetailOrder> selectWmsOutStockDetailOrderList(WmsOutStockDetailOrder wmsOutStockDetailOrder)
    {
        return wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderList(wmsOutStockDetailOrder);
    }

    /**
     * 新增出库单明细
     *
     * @param wmsOutStockDetailOrder 出库单明细
     * @return 结果
     */
    @Override
    public int insertWmsOutStockDetailOrder(WmsOutStockDetailOrder wmsOutStockDetailOrder)
    {
        WmsOutStockDetailOrder select = new WmsOutStockDetailOrder();
        select.setOrderNo(wmsOutStockDetailOrder.getOrderNo());
        select.setProductNo(wmsOutStockDetailOrder.getProductNo());
        List<WmsOutStockDetailOrder> list = wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderList(select);
        if(!list.isEmpty()){
            throw new ServiceException("物料不能重复");
        }
        wmsOutStockDetailOrder.setNo(java.util.UUID.randomUUID().toString());
        wmsOutStockDetailOrder.setCreateBy(SecurityUtils.getUsername());
        wmsOutStockDetailOrder.setCreateTime(DateUtils.getNowDate());
        wmsOutStockDetailOrder.setOrderDetailStatus(OutOrderStatusEnum.NEW.getCode());
        return wmsOutStockDetailOrderMapper.insertWmsOutStockDetailOrder(wmsOutStockDetailOrder);
    }

    /**
     * 修改出库单明细
     *
     * @param wmsOutStockDetailOrder 出库单明细
     * @return 结果
     */
    @Override
    public int updateWmsOutStockDetailOrder(WmsOutStockDetailOrder wmsOutStockDetailOrder)
    {
        wmsOutStockDetailOrder.setUpdateBy(SecurityUtils.getUsername());
        wmsOutStockDetailOrder.setUpdateTime(DateUtils.getNowDate());
        return wmsOutStockDetailOrderMapper.updateWmsOutStockDetailOrder(wmsOutStockDetailOrder);
    }

    /**
     * 批量删除出库单明细
     *
     * @param ids 需要删除的出库单明细主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWmsOutStockDetailOrderByIds(Long[] ids)
    {
        WmsOutStockDetailOrder detailOrder = new WmsOutStockDetailOrder();
        detailOrder.setIds(Arrays.asList(ids));
        List<WmsOutStockDetailOrder> list = wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderList(detailOrder);
        if(list.isEmpty()){
            return 0;
        }else{
            //校验详情对应的拣货单
            List<String> errorNos = list.stream()
                    .filter(e ->  e.getPickingQty()!=null &&  e.getPickingQty()> 0)
                    .map(WmsOutStockDetailOrder::getNo).collect(Collectors.toList());
            if(!errorNos.isEmpty()) {
                throw new ServiceException("已有实际入库数量的数据不能删除");
            }
        }

        int response = wmsOutStockDetailOrderMapper.deleteWmsOutStockDetailOrderByIds(ids);
        if(response > 0){
            //删除关联的拣货单
            List<String> delNoList = list.stream().map(WmsOutStockDetailOrder::getPickerTaskOrderNo)
                    .filter(StringUtils::isEmpty).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(delNoList)){
                String[] delNos = delNoList.toArray(new String[delNoList.size()]);
                pickerTaskOrderService.deletePickerTaskOrderByNos(delNos);
            }
        }
        return response;
    }

    /**
     * 删除出库单明细信息
     *
     * @param id 出库单明细主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWmsOutStockDetailOrderById(Long id)
    {
        WmsOutStockDetailOrder detailOrder = wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderById(id);
        if(detailOrder == null){
            return 0;
        }else if(detailOrder.getPickingQty() > 0){
            throw new ServiceException("已有实际入库数量的数据不能删除");
        }
        int response = wmsOutStockDetailOrderMapper.deleteWmsOutStockDetailOrderById(id);
        if(response > 0 && StringUtils.isNotEmpty(detailOrder.getPickerTaskOrderNo())){
            pickerTaskOrderService.deletePickerTaskOrderByNo(detailOrder.getPickerTaskOrderNo());
        }
        return response;
    }

    /**
     * 根据出库单列表删除详情信息
     *
     * @param nos 出库单编号列表
     * @return 结果
     */
    @Override
    public int deleteByOrderNos(List<String> nos) {
        return wmsOutStockDetailOrderMapper.deleteByOrderNos(nos);
    }

    /**
     * 分配拣货
     *
     * @param entity 分配信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int distributePickerTask(distributePickerVo entity){
        //是否已备料 默认为否
        String whetherMp = YNEnum.N.getCode();
        if(StringUtils.isEmpty(entity.getPicker())){
            throw new ServiceException("拣货员不能为空");
        }
        if (StringUtils.isEmpty(entity.getStorehouseNo())){
            throw new ServiceException("仓库不能为空");
        }
        if (entity.getDistributeQty()==null){
            throw new ServiceException("分配数量不能为空");
        }
        WmsOutStockDetailOrder detailOrder = wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderById(entity.getId());
        if(detailOrder == null){
            throw new ServiceException("该明细不存在");
        }
        WmsOutStockOrder order = wmsOutStockOrderService.selectWmsOutStockOrderByNo(detailOrder.getOrderNo());
        if(order == null){
            throw new ServiceException("出库单不存在");
        }
        //判断拣货单的分配数量是否大于申请数量
        List<PickerTaskOrder> pickerTaskOrderList = pickerTaskOrderService.selectPickerTaskOrderByOutOrderId(detailOrder.getId());
        //总分配数量
        Long totalDistributeQty = 0L;
        if (CollectionUtil.isNotEmpty(pickerTaskOrderList)){
            totalDistributeQty = pickerTaskOrderList.stream().map(e -> e.getDistributeQty()).reduce(Long::sum).get();
        }
        totalDistributeQty = totalDistributeQty + entity.getDistributeQty();
        if(totalDistributeQty>detailOrder.getOrderQty()){
            throw new ServiceException("分配总数不能大于需求数量");
        }
        PickerTaskOrder  pickerTaskOrder = null;
        if (entity.getPickId()!=null){
            pickerTaskOrder = this.pickerTaskOrderService.selectPickerTaskOrderById(entity.getPickId());
        }
        if(pickerTaskOrder != null && !OutOrderStatusEnum.NEW.getCode().equals(pickerTaskOrder.getStatus())){
            throw new ServiceException("拣货单只能在新建状态下修改");
        }else if(pickerTaskOrder == null || !detailOrder.getStorehouseNo().equals(entity.getStorehouseNo())){
            WmsStorehouse storehouse = wmsStorehouseService.selectWmsStorehouseByNo(entity.getStorehouseNo());
            if(storehouse == null){
                throw new ServiceException("该仓库不存在");
            }
            //校验出库权限
            this.storehousePermissionCheckout(entity.getStorehouseNo(), order.getOrderType());
            //校验库存
            if(StoreHouseTypeEnum.DJC.getCode().equals(storehouse.getTypeNo())){
                StorehouseStockCheck check = new StorehouseStockCheck();
                if (StringUtils.isNotEmpty(entity.getStorehouseAreaNo())){
                    check.setStorehouseAreaNo(entity.getStorehouseAreaNo());
                }
                check.setStorehouseNo(entity.getStorehouseNo());
                check.setProductNo(detailOrder.getProductNo());
                List<StorehouseStockCheck> checks = storehouseStockCheckService.selectStorehouseStockCheckList(check);
                Long num = checks.stream().mapToLong(StorehouseStockCheck::getQty).sum();
                List<StockOccupyDetail> occupyDetails = stockOccupyDetailService.getStockOccupyDetailByStorehouseNoProductNo(storehouse.getNo(),detailOrder.getProductNo(), StockOccupyTypeEnum.WAIT_INSPECTION_FREEZE.getCode());
                long occupyNum = occupyDetails.stream().mapToLong(StockOccupyDetail::getOccupyQty).sum();
                num = num - occupyNum;
                if (entity.getDistributeQty() > num) {
                    throw new ServiceException("库存不足");
                }
            }else {
                WmsStorehouseStock stock = new WmsStorehouseStock();
                stock.setStorehouseNo(entity.getStorehouseNo());
                stock.setProductNo(detailOrder.getProductNo());
                if (StringUtils.isNotEmpty(entity.getStorehouseAreaNo())){
                    stock.setStorehouseAreaNo(entity.getStorehouseAreaNo());
                }
                //如果是领料出库单,需要校验是否已备料，如果已备料就查备料库存是否充足
                if (order.getOrderType()==OutStockOrderTypeEnum.PICK.getCode()){
                   PickProductBill pickProductBill = pickProductBillService.selectPickProductBillByNo(order.getRelOrderNo());
                   if (pickProductBill!=null){
                       if(YNEnum.Y.getCode().equals(pickProductBill.getWhetherMp())){
                           whetherMp = YNEnum.Y.getCode();
                           stock.setWorkOrderNo(order.getWorkOrderNo());
                       }
                   }
                }
                stock.setWhetherMp(whetherMp);
                List<WmsStorehouseStock> stocks = wmsStorehouseStockService.selectWmsStorehouseStockList(stock);
                Long num = stocks.stream().mapToLong(WmsStorehouseStock::getQty).sum();
                List<StockOccupyDetail> occupyDetails = stockOccupyDetailService.getStockOccupyDetailByStorehouseNoProductNo(storehouse.getNo(),detailOrder.getProductNo(), StockOccupyTypeEnum.OCCUPY.getCode());
                long occupyNum = occupyDetails.stream().mapToLong(StockOccupyDetail::getOccupyQty).sum();
                num = num - occupyNum;
                if (entity.getDistributeQty() > num) {
                    throw new ServiceException("库存不足");
                }
            }
        }else if(detailOrder.getStorehouseNo().equals(entity.getStorehouseNo())){
            //相同的仓库就不用执行后面的流程
            pickerTaskOrder.setPicker(entity.getPicker());
            return pickerTaskOrderService.updatePickerTaskOrder(pickerTaskOrder);
        }
        if(pickerTaskOrder != null){
            //解除旧占用
            wmsStockOccupyService.stockOccupyCancel(pickerTaskOrder.getNo());
            wmsStockOccupyService.deleteWmsStockOccupyById(pickerTaskOrder.getId());
            pickerTaskOrderService.deletePickerTaskOrderById(pickerTaskOrder.getId());
        }
        //新增拣货单
        pickerTaskOrder = new PickerTaskOrder();
        pickerTaskOrder.setType(order.getOrderType());
        pickerTaskOrder.setStatus(OutOrderStatusEnum.NEW.getCode());
        pickerTaskOrder.setRelOrderNo(order.getRelOrderNo());
        pickerTaskOrder.setProductNo(entity.getProductNo());
        pickerTaskOrder.setOrderQty(detailOrder.getOrderQty());
        pickerTaskOrder.setStorehouseNo(entity.getStorehouseNo());
        pickerTaskOrder.setStorehouseAreaNo(entity.getStorehouseAreaNo());
        pickerTaskOrder.setPicker(entity.getPicker());
        pickerTaskOrder.setDistributeQty(entity.getDistributeQty());
        pickerTaskOrder.setOutOrderId(entity.getId());
        pickerTaskOrderService.insertPickerTaskOrder(pickerTaskOrder);
        //如果主表数据状态是新建就要改成分配中
        if(OutOrderStatusEnum.NEW.getCode().equals(order.getOrderStatus())){
            WmsOutStockOrder outStockOrder = new WmsOutStockOrder();
            outStockOrder.setId(order.getId());
            outStockOrder.setOrderStatus(OutOrderStatusEnum.DISTRIBUTE.getCode());
            wmsOutStockOrderService.updateWmsOutStockOrder(outStockOrder);
        }
        if (OutOrderStatusEnum.NEW.getCode().equals(detailOrder.getOrderDetailStatus())){
            detailOrder.setOrderDetailStatus(OutOrderStatusEnum.DISTRIBUTE.getCode());
            this.updateWmsOutStockDetailOrder(detailOrder);
        }
        //库存占用处理
        String taskNo = pickerTaskOrder.getNo();
        String storehouseNo = pickerTaskOrder.getStorehouseNo();
        String productNo = pickerTaskOrder.getProductNo();
        Long orderQty = pickerTaskOrder.getDistributeQty();
        wmsStockOccupyService.stockOccupy(taskNo,storehouseNo, productNo, orderQty,order.getWorkOrderNo(),pickerTaskOrder.getStorehouseAreaNo(),whetherMp);
        //关联单据的状态修改
        Integer status = OutOrderStatusEnum.PICKING.getCode();
        if(!StringUtils.isEmpty(order.getRelOrderNo())
                && OutStockOrderTypeEnum.SALES.getCode().equals(order.getOrderType())) {
            //销售单
            WmsSalesOrder salesOrder = wmsSalesOrderService.selectWmsSalesOrderByNo(order.getRelOrderNo());
            if (!status.equals(salesOrder.getOrderStatus())) {
                salesOrder.setOrderStatus(status);
                wmsSalesOrderService.updateWmsSalesOrder(salesOrder);
            }
        }else if(!StringUtils.isEmpty(order.getRelOrderNo())
                && OutStockOrderTypeEnum.PICK.getCode().equals(order.getOrderType())) {
            //领料单
            PickProductBill bill = pickProductBillService.selectPickProductBillByNo(order.getRelOrderNo());
            if (!status.equals(bill.getStatus())) {
                bill.setStatus(status);
                pickProductBillService.updatePickProductBill(bill);
            }
        }else if(!StringUtils.isEmpty(order.getRelOrderNo())
                && OutStockOrderTypeEnum.ADJUST.getCode().equals(order.getOrderType())) {
            //调拨出库单
            AdjustOutBill bill = adjustOutBillService.selectAdjustOutBillByNo(order.getRelOrderNo());
            if (!status.equals(bill.getStatus())) {
                bill.setStatus(status);
                adjustOutBillService.updateAdjustOutBill(bill);
            }
        }else if(OutStockOrderTypeEnum.RETURN.getCode().equals(order.getOrderType())){
            //退货出库
            PurchaseReturnBill bill = purchaseReturnBillService.selectPurchaseReturnBillByNo(order.getRelOrderNo());
            if(!status.equals(bill.getStatus())){
                bill.setStatus(status);
                purchaseReturnBillService.updatePurchaseReturnBill(bill);
            }
        }
        return 1;
    }

    @Override
    public int batchInsertOutStockDetailOrder(List<WmsOutStockDetailOrder> outStockDetailOrderList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (WmsOutStockDetailOrder outStockDetailOrder : outStockDetailOrderList){
            if(StringUtils.isBlank(outStockDetailOrder.getNo())){
                outStockDetailOrder.setNo(TableNoUtil.getNo(WmsOutStockDetailOrder.class));
            }
            outStockDetailOrder.setCreateBy(username);
            outStockDetailOrder.setCreateTime(currerTime);
        }
        int insertNum = 0;
        for (int i=0; i<outStockDetailOrderList.size();) {
            int endIndex = i+500;
            if (endIndex > outStockDetailOrderList.size()) {
                endIndex = outStockDetailOrderList.size();
            }
            insertNum = insertNum + wmsOutStockDetailOrderMapper.batchInsertOutStockDetailOrder(outStockDetailOrderList.subList(i, endIndex));
            i = endIndex;
        }
        return insertNum;
    }

    /**
     * 仓库权限校验
     * @param storehouseNo  仓库编号
     * @param type          出库类型
     */
    private void storehousePermissionCheckout(String storehouseNo, Integer type){
        //校验仓库是否具有权限
        StorehousePermission permission = storehousePermissionService.getPermissionsByStorehouseNo(storehouseNo);
        if(permission == null){
            return;
        }
        List<String> permissionDetails = Arrays.asList(permission.getPermissionDetail().split(","));
        List<String> outPermissionList = Arrays.asList(
                StorehousePermissionEnum.OUT_SALES.getCode().toString(),
                StorehousePermissionEnum.OUT_PICK.getCode().toString(),
                StorehousePermissionEnum.OUT_ADJUST.getCode().toString(),
                StorehousePermissionEnum.OUT_OTHER.getCode().toString(),
                StorehousePermissionEnum.OUT_RETURN.getCode().toString()
        );
        //权限校验
        if(outPermissionList.size() >= type && permissionDetails.contains(outPermissionList.get(type - 1))){
            return;
        }
        throw new ServiceException("该仓库权限不足");
    }

    /**
     * 确认分配
     * @param id
     * @return
     */
   public int confirmDistribute(Long id){
        WmsOutStockDetailOrder outStockDetailOrder = this.wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderById(id);
        if (outStockDetailOrder==null){
            throw new ServiceException("找不到明细数据");
        }
        //校验是否有分配拣货员
        List<PickerTaskOrder> pickerTaskOrderList = this.pickerTaskOrderService.selectPickerTaskOrderByOutOrderId(outStockDetailOrder.getId());
        if (CollectionUtil.isEmpty(pickerTaskOrderList)){
            throw new ServiceException("请先分配拣货员");
        }else{
            //将所有拣货单状态调整为待检
            pickerTaskOrderList.stream().forEach(e->{
                e.setStatus(OutOrderStatusEnum.WAITING_PICK.getCode());
            });
            this.pickerTaskOrderService.batchUpdatePickerTaskOrder(pickerTaskOrderList);
            outStockDetailOrder.setOrderDetailStatus(OutOrderStatusEnum.PICKING.getCode());
            this.wmsOutStockDetailOrderMapper.updateWmsOutStockDetailOrder(outStockDetailOrder);
        }
        return 1;
    }

    @Override
    public List<WmsOutStockDetailOrder> listByOrderNo(String orderNo) {
        WmsOutStockDetailOrder query = new WmsOutStockDetailOrder();
        query.setOrderNo(orderNo);
        return this.wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderList(query);
    }

    @Override
    public Long outStockDetailOrderAvailableQty(OutStockDetailOrderAvailableQtyVo vo) {
        WmsStorehouse storehouse = wmsStorehouseService.selectWmsStorehouseByNo(vo.getStorehouseNo());
        if(storehouse == null){
            throw new ServiceException("该仓库不存在");
        }
        WmsOutStockDetailOrder detailOrder = wmsOutStockDetailOrderMapper.selectWmsOutStockDetailOrderById(vo.getDetailId());
        WmsOutStockOrder outStockOrder = this.wmsOutStockOrderService.selectWmsOutStockOrderByNo(detailOrder.getOrderNo()) ;
        if (outStockOrder == null){
            throw new ServiceException("出库单不存在");
        }
        long num = 0L;
        //校验库存
        if(StoreHouseTypeEnum.DJC.getCode().equals(storehouse.getTypeNo())){
            StorehouseStockCheck stockCheck = new StorehouseStockCheck();
            stockCheck.setStorehouseNo(storehouse.getNo());
            stockCheck.setProductNo(detailOrder.getProductNo());
            List<StorehouseStockCheck> checks = storehouseStockCheckService.selectStorehouseStockCheckList(stockCheck);
            num = checks.stream().mapToLong(StorehouseStockCheck::getQty).sum();
            List<StockOccupyDetail> occupyDetails = stockOccupyDetailService.getStockOccupyDetailByStorehouseNoProductNo(storehouse.getNo(),detailOrder.getProductNo(), StockOccupyTypeEnum.WAIT_INSPECTION_FREEZE.getCode());
            long occupyNum = occupyDetails.stream().mapToLong(StockOccupyDetail::getOccupyQty).sum();
            num = num - occupyNum;
        }else {
            //是否已备料 默认为否
            String whetherMp = YNEnum.N.getCode();
            if (outStockOrder.getOrderType()==OutStockOrderTypeEnum.PICK.getCode()){
               PickProductBill pickProductBill =  pickProductBillService.selectPickProductBillByNo(outStockOrder.getRelOrderNo());
               if (pickProductBill!=null){
                   if (pickProductBill.getWhetherMp().equals(YNEnum.Y.getCode())){
                       whetherMp = YNEnum.Y.getCode();
                   }
               }
            }
            List<WmsStorehouseStock> stockList = this.wmsStorehouseStockService.getStock(storehouse.getNo(),detailOrder.getProductNo(),null,vo.getAreaNo(),whetherMp,outStockOrder.getWorkOrderNo());
            num = stockList.stream().filter(e->(e.getStatus().equals(StorehouseStockStatusEnum.NORMAL.getCode()))||e.getStatus().equals(StorehouseStockStatusEnum.POOR.getCode())).mapToLong(WmsStorehouseStock::getQty).sum();
            List<StockOccupyDetail> occupyDetails = stockOccupyDetailService.getStockOccupyDetailByStorehouseNoProductNo(storehouse.getNo(),detailOrder.getProductNo(), StockOccupyTypeEnum.OCCUPY.getCode());
            long occupyNum = occupyDetails.stream().mapToLong(StockOccupyDetail::getOccupyQty).sum();
            num = num - occupyNum;
        }
        if(num<0){
            num = 0;
        }
       return num;
    }
}
